package com.org.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.octo.captcha.service.CaptchaServiceException;
import com.org.utils.jcaptcha.JCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 *@Author:liangjilong
 *@Date:2014-3-30
 *@CopyRight:liangjilong
 *@Version:1.0
 */
@Controller
public class ImagesController {

	@RequestMapping(value="/jcaptcha.do")
	public void initCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// flush it in the response
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		byte[] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			String captchaId = request.getSession().getId();
			// call the ImageCaptchaService getChallenge method
			BufferedImage challenge = JCaptchaService.getInstance().getImageChallengeForID(captchaId,request.getLocale());

			// a jpeg encoder
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream);
			jpegEncoder.encode(challenge);
		} catch (IllegalArgumentException e) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		} catch (CaptchaServiceException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}

		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

		ServletOutputStream responseOutputStream = response.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	
	}
	public void initJCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Boolean isResponseCorrect = Boolean.FALSE;
		// remenber that we need an id to validate!
		String captchaId = request.getSession().getId();
		System.out.println("captchaId---" + captchaId);

		// retrieve the response
		String resp = request.getParameter("j_captcha_response");
		System.out.println("j_captcha_response---" + resp);

		// Call the Service method
		isResponseCorrect = JCaptchaService.getInstance().validateResponseForID(captchaId, resp);
		System.out.println("isResponseCorrect---" + isResponseCorrect);

		if (isResponseCorrect == true) {
			System.out.println("success..");
		} else {
			System.out.println("FAIL..");
		}
	}
}
